package com.software.levelupandroid.loginAndRegistration;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
import com.software.levelupandroid.MainActivity;
import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Result;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.entity.UserCodeDTO;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class RegisterActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private Button registerButton, btnVerify;
    private EditText emailEditText, passwordEditText, confirmPasswordEditText, nameEditText, verifyCodeEditText;
    private String email, password, confirmPassword, name, code;
    private MyListener myReListener;
    private OkHttpClient okHttpClient;
    private Response response;
    private Gson gson;
    private Result result;
    private String responseContent,getCodeForRegisterServerPath,registerServerPath;
    private String cookie;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        findViews();

        initToolbar();
        okHttpClient = new OkHttpClient()
                .newBuilder()
                .connectTimeout(60,TimeUnit.SECONDS)
                .readTimeout(60,TimeUnit.SECONDS)
                .build();
        gson = new Gson();
        setListener();
    }

    private void initToolbar() {
        toolbar = findViewById(R.id.toolbar_register);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }

    private void setListener() {
        myReListener = new MyListener();
        registerButton.setOnClickListener(myReListener);
        btnVerify.setOnClickListener(myReListener);
    }
    private void InitData() {
        email = emailEditText.getText().toString();
        password = passwordEditText.getText().toString();
        confirmPassword = confirmPasswordEditText.getText().toString();
        name = nameEditText.getText().toString();
        code = verifyCodeEditText.getText().toString();
    }

    class MyListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            String msg = "";
            switch (v.getId()) {
                case R.id.register_button:
                    InitData();
                    //todo 账号是否已经注册
                    if(!password.equals(confirmPassword)){
                        msg += "两次密码输入不一致，请重新输入";
                    }else if (password.length() < 6){
                        msg += "密码长度不能小于6位，请重新输入";
                    }else if (email == null || email.equals("")){
                        msg += "邮箱不能为空，请重新输入";
                    }else if (name == null || name.equals("")){
                        msg += "用户名不能为空，请重新输入";
                    }else if (password == null || password.equals("")){
                        msg += "密码不能为空，请重新输入";
                    }else if (confirmPassword == null || confirmPassword.equals("")){
                        msg += "两次密码输入不一致，请重新输入";
                    }else if (code == null || verifyCodeEditText.equals("")){
                        msg += "验证码不能为空，请重新输入";
                    }
                    if(msg.equals("")) {
                        register(name,email,password,code);
                        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                        startActivity(intent);
                    }else {
                        Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.btn_verify:
                    email = emailEditText.getText().toString();
                    if(check(email)){
                        countCode();
                        receiveCode(email);
                    }
                    else
                        Toast.makeText(RegisterActivity.this, "邮箱格式不正确", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    }
    public static boolean check(String str) {
        String patt="^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$";
        Pattern r = Pattern.compile(patt);
        Matcher matcher = r.matcher(str);
        return matcher.find();
    }
    private void register(String name, String password, String email, String code) {
        String userDTO = gson.toJson(new UserCodeDTO(new User(name,email,password),code));
        registerServerPath = getApplicationContext().getString(R.string.registerServerPath);
        System.out.println(registerServerPath);
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json"),
                userDTO
        );
        Request request = new Request.Builder()
                .post(requestBody)
                .post(requestBody)
                .header("Cookie",cookie)
                .url(registerServerPath)
                .build();
        Call call = okHttpClient.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    response = call.execute();
                    responseContent = response.body().string();
                    result = gson.fromJson(responseContent, Result.class);
                    if(result.getCode().equals("200")){
                        showToast("注册成功！");
                    }else
                        showToast("验证码错误！");
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    showToast(e.getMessage());
                }
            }
        }).start();
    }

    private void receiveCode(String email) {
        getCodeForRegisterServerPath = getApplicationContext().getString(R.string.getCodeForRegisterServerPath);
        System.out.println(getCodeForRegisterServerPath);
        String url = getCodeForRegisterServerPath + "?email=" + email;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    response = okHttpClient.newCall(request).execute();
                    cookie = response.header("Set-Cookie");
                    System.out.println(cookie);
                    responseContent = response.body().string();
                    Result result = gson.fromJson(responseContent, Result.class);
                    if(result.getCode().equals("200")){
                        showToast("验证码发送成功！");
                    }else {
                        System.out.println(result.getMessage());
                        showToast("该邮箱已注册！");
                    }
                } catch (Exception e) {
                    showToast("与服务器连接失败！");
                    System.out.println(e.getMessage());
                }
            }
        }).start();

    }

    private void showToast(String content) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RegisterActivity.this, content, Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void findViews() {
        registerButton = findViewById(R.id.register_button);
        emailEditText = findViewById(R.id.register_email);
        passwordEditText = findViewById(R.id.register_pwd);
        confirmPasswordEditText = findViewById(R.id.register_confirm_pwd);
        nameEditText = findViewById(R.id.register_name);
        verifyCodeEditText = findViewById(R.id.verify_code);
        btnVerify = findViewById(R.id.btn_verify);
    }

    private void countCode(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
                    @Override
                    public void onTick(long l) {
                        btnVerify.setEnabled(false);
                        btnVerify.setText(l/1000 + "秒后重发");
                    }

                    @Override
                    public void onFinish() {
                        btnVerify.setEnabled(true);
                        btnVerify.setText("获取验证码");
                    }
                };
                countDownTimer.start();
            }
        });
    }
}